import config from '../config.js'
import store from '@/store'

/**
 * 合并路径
 * @param {String} value - 传入的路径后缀
 */
function mergeUrl(value) {
  return (config.url + (value.indexOf('/') == 0 ? value : '/' + value))
}

let promiseArr = []

/**
 * 取消pending的重复请求
 * */
let removePending = (url) => {
  promiseArr.forEach((item, index) => {
    // 这个接口需要请求两次，不能取消
    if (item.url.includes('/third/ssdcitycode/list')) {
      return
    }
    if (item.url === url) {
      item.cancel ? item.cancel.abort() : null
      promiseArr.splice(index, 1)
    }
  })
}

let flag = false
/**
 * 请求主体
 * @param {String} method - 请求类型 GET/POST...
 * @param {String} url - 路径后缀
 * @param {Object} data - 请求参数
 * @param {Object} headers - 请求头
 * @returns {Promise} - 返回promise 
 */
const apiRequest = (method, url, data, headers = null) => {

  let mixHeaders = {
    'content-type': 'application/json;charset=UTF-8',
    'DT_TOKEN': store.state.user.token || null,
    ...headers
  }

  // 请求拦截
  removePending(url)

  return new Promise((resolve, reject) => {
    const requestTask = uni.request({
      method,
      url: mergeUrl(url),
      data,
      header: mixHeaders,
      success: (res) => {
        // 请求完成后清除数组
        removePending(url)

        if (res.data.code == 0) {

          flag = false

          resolve(res.data)
        } else {
          if (res.data.code == 402) {
            if (flag) return
            flag = true
            store.dispatch("user/logOut")

            uni.redirectTo({
              url: '/pages/entrance/login/login'
            })

            setTimeout(() => {
              uni.showToast({
                title: '登录已过期，请重新登录',
                icon: 'none',
                duration: 2000
              });
            })

          } else {
            reject(res.data)

            uni.showToast({
              title: res.data.msg,
              icon: 'none'
            });
          }
        }
      },
      fail: (err) => {
				reject(err)
        uni.showToast({
          title: '网络异常，请稍后重试！',
          icon: 'none',
          duration: 2000
        });
			}
    });

    promiseArr.push({
      url,
      cancel: requestTask
    })

  })
}

export default {
  get(url, param, headers) {
    return apiRequest('GET', url, param, headers)
  },
  post(url, param, headers) {
    return apiRequest('POST', url, param, headers)
  },
  put(url, param, headers) {
    return apiRequest('PUT', url, param, headers)
  },
  delete(url, param, headers) {
    return apiRequest('DELETE', url, param, headers)
  }
}